package ui;

import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import servicios.GenericBusinessException;
import util.GuiUtilities;
import dominio.Cliente;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class UICliente extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JLabel lblNombre = null;
	private JLabel lblApellido = null;
	private JTextField txtNombre = null;
	private JTextField txtPrioridad = null;
	private JScrollPane jScrollPane = null;
	private JTable jTable = null;
	private JButton btnNuevo = null;
	private JButton btnAgregar = null;
	private JButton btnBorrar = null;
	private JButton btnCancelar = null;
	private JButton btnBuscar = null;
	private DefaultTableModel tabModel = null;
	private JLabel lblOid = null;
	private JTextField txtOid = null;

	/**
	 * This is the default constructor
	 * @param telefonista 
	 */
	public UICliente() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(497, 452);
		this.setContentPane(getJContentPane());
		this.setTitle("Administracion Clientes");
		actualizarLista();
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	public JPanel getJContentPane() {
		if (jContentPane == null) {
			lblOid = new JLabel();
			lblOid.setBounds(new Rectangle(12, 11, 78, 20));
			lblOid.setText("ID");
			lblApellido = new JLabel();
			lblApellido.setBounds(new Rectangle(12, 63, 78, 20));
			lblApellido.setText("Prioridad");
			lblNombre = new JLabel();
			lblNombre.setBounds(new Rectangle(12, 37, 78, 20));
			lblNombre.setText("Nombre");
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(lblNombre, null);
			jContentPane.add(lblApellido, null);
			jContentPane.add(getTxtNombre(), null);
			jContentPane.add(getTxtPrioridad(), null);
			jContentPane.add(getJScrollPane(), null);
			jContentPane.add(getBtnNuevo(), null);
			jContentPane.add(getBtnAgregar(), null);
			jContentPane.add(getBtnBorrar(), null);
			jContentPane.add(getBtnCancelar(), null);
			jContentPane.add(getBtnBuscar(), null);
			jContentPane.add(lblOid, null);
			jContentPane.add(getTxtOid(), null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes txtNombre	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTxtNombre() {
		if (txtNombre == null) {
			txtNombre = new JTextField();
			txtNombre.setBounds(new Rectangle(100, 37, 133, 20));
		}
		return txtNombre;
	}

	/**
	 * This method initializes txtApellido	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTxtPrioridad() {
		if (txtPrioridad == null) {
			txtPrioridad = new JTextField();
			txtPrioridad.setBounds(new Rectangle(100, 63, 133, 20));
		}
		return txtPrioridad;
	}

	
	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new Rectangle(6, 155, 474, 263));
			jScrollPane.setViewportView(getJTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jTable	
	 * 	
	 * @return javax.swing.JTable	
	 */
	@SuppressWarnings("serial")
	private JTable getJTable() {
		if (jTable == null) {
			
			jTable = new JTable(getTabModel()){
				public boolean isCellEditable(int row, int column)
				{
					return false;
				}};
				jTable.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent e) {
						if (e.getClickCount() > 1) {
							getClienteSelected();
						}else{
							setClienteSelected();
						
						}
					}
				});
		}
		return jTable;
	}

	public void getClienteSelected() {
		int idCliente=Integer.parseInt(getJTable().getValueAt(getJTable().getSelectedRow(), 0).toString());
		if(idCliente!=0){
			Cliente c;
			try {
				c = Fachada.buscarCliente(idCliente);

			if(c!=null){
				cargarCliente(c);
				dispose();
			}
			} catch (GenericBusinessException e1) {
				GuiUtilities.showError(this,e1.getMessage());
			}
		}
	}

	private void cargarCliente(Cliente c) {
		txtPrioridad.setText(Integer.toString(c.getPrioridad()));
		txtNombre.setText(c.getNombre());
		
	}

	@SuppressWarnings("unchecked")
	protected void setClienteSelected() {
		int laRow=getJTable().getSelectedRow();
		txtOid.setText((Integer.toString((Integer)((Vector) getTabModel().getDataVector().elementAt(laRow)).elementAt(0))));
		txtNombre.setText((String)((Vector) getTabModel().getDataVector().elementAt(laRow)).elementAt(1));
		txtPrioridad.setText((Integer.toString((Integer)((Vector) getTabModel().getDataVector().elementAt(laRow)).elementAt(2))));
		
	}

	public void selectCell(int row,int col){
         if(row!=-1 && col !=-1){
        	 getJTable().setRowSelectionInterval(row,row);
        	 getJTable().setColumnSelectionInterval(col,col);
          }
    }
	
	
	
	/**
	 * This method initializes btnNuevo	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnNuevo() {
		if (btnNuevo == null) {
			btnNuevo = new JButton();
			btnNuevo.setBounds(new Rectangle(335, 16, 139, 25));
			btnNuevo.setText("Nuevo");
			btnNuevo.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					nuevoCliente();
				}
			});
		}
		return btnNuevo;
	}

	protected void nuevoCliente() {
		borrarCampos();
		txtOid.setText("");
	}

	private void borrarCampos() {
		txtNombre.setText("");
		txtPrioridad.setText("");
		
	}

	/**
	 * This method initializes btnAgregar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnAgregar() {
		if (btnAgregar == null) {
			btnAgregar = new JButton();
			btnAgregar.setBounds(new Rectangle(335, 50, 139, 25));
			btnAgregar.setText("Agregar/Modificar");
			btnAgregar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
						guardar();
				}
			});
		}
		return btnAgregar;
	}

	protected void guardar()  {
		if(validoCampos()){
			Cliente unCliente=new Cliente();
			if(!txtOid.getText().equals("")){
				unCliente.setId(Integer.parseInt(txtOid.getText()));	
			}else{
				unCliente.setId(0);
			}
			unCliente.setPrioridad(Integer.parseInt(txtPrioridad.getText()));
			unCliente.setNombre(txtNombre.getText());
			try {
				Fachada.guardarCliente(unCliente);
			} catch (Exception e) {
				GuiUtilities.showError(this,e.getMessage());
			}
			txtOid.setText("");
			borrarCampos();
			actualizarLista();
		}
	}


	private boolean validoCampos()  {
		try{
		if(Integer.parseInt(txtPrioridad.getText())<1||
				Integer.parseInt(txtPrioridad.getText())>5){
			GuiUtilities.showError(this,"Error en Prioridad, solo valores de 1 a 5");
		}else{
			if(txtNombre.getText().equals("")){
				GuiUtilities.showError(this,"El nombre no puede ser vacio");
				return false;
			}
			return true;
		}
		}catch(NumberFormatException e){
			GuiUtilities.showError(this,"Error en Prioridad, solo valores de 1 a 5");
		}
			return false;
		}
		
	

	@SuppressWarnings("unchecked")
	private void actualizarLista() {
		getJTable().removeAll();
		List resultado = new ArrayList();
		try {
			resultado=Fachada.getListaClientes();
		} catch (Exception e) {
			GuiUtilities.showError(this,e.getMessage());
		}
		if(!resultado.isEmpty()){
			Vector<String> columns=new Vector<String>();
			String[] columnnames={ 
					"Id","Nombre","Prioridad"
			};
			for(int i=0;i<columnnames.length;i++)
				columns.addElement((String) columnnames[i]);
			tabModel.setRowCount(resultado.size());
			Vector lasRows=new Vector();
			for(int x=0;x<resultado.size();x++){
				Vector unaRow=new Vector();
				Cliente unCliente=(Cliente)resultado.get(x);
				unaRow.add(unCliente.getId());
				unaRow.add(unCliente.getNombre());
				unaRow.add(unCliente.getPrioridad());
				lasRows.add(unaRow);
			}
			tabModel.setDataVector(lasRows, columns);
		}else{
			tabModel.setRowCount(0);
		}
	}

	

	/**
	 * This method initializes btnBorrar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnBorrar() {
		if (btnBorrar == null) {
			btnBorrar = new JButton();
			btnBorrar.setBounds(new Rectangle(335, 84, 139, 25));
			btnBorrar.setText("Borrar");
			btnBorrar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					borrarSelected();
				}
			});
		}
		return btnBorrar;
	}

	protected void borrarSelected() {
		if(!txtOid.getText().equals("")){
			Cliente unCliente=new Cliente();
			unCliente.setId(Integer.parseInt(txtOid.getText()));
			try {
				if(Fachada.eliminar(unCliente)){
					borrarCampos();
					txtOid.setText("");
					actualizarLista();
				}else{
					GuiUtilities.showError(this,"No se puede eliminar Cliente con Pedidos");
				}
				
			} catch (Exception e) {
				GuiUtilities.showError(this,e.getMessage());
			}
			
		}
	}

	/**
	 * This method initializes btnCancelar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnCancelar() {
		if (btnCancelar == null) {
			btnCancelar = new JButton();
			btnCancelar.setBounds(new Rectangle(335, 118, 139, 25));
			btnCancelar.setText("Cancelar");
			btnCancelar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					UICliente.this.dispose();
				}
			});
		}
		return btnCancelar;
	}

	private DefaultTableModel getTabModel(){
		if(tabModel==null){
		tabModel=new DefaultTableModel();
		Vector<String> rows = new Vector<String>();
		Vector<String> columns=new Vector<String>();
		String[] columnnames={"Id","Nombre","Prioridad"}; 
		for(int i=0;i<columnnames.length;i++)
			columns.addElement((String) columnnames[i]);
		tabModel.setDataVector(rows,columns);
		return tabModel;
		}else{
			return tabModel;
		}
		
	}
	
	
	
	/**
	 * This method initializes btnBuscar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnBuscar() {
		if (btnBuscar == null) {
			btnBuscar = new JButton();
			btnBuscar.setBounds(new Rectangle(239, 63, 79, 21));
			btnBuscar.setText("Buscar");
			btnBuscar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					buscarDatosXNombre();
				}
			});
		}
		return btnBuscar;
	}
	
	@SuppressWarnings("unchecked")
	protected void buscarDatosXNombre() {
		List<Cliente> resultado = new ArrayList<Cliente>();
		try {
			resultado=Fachada.buscarClienteXNombre(txtNombre.getText());
		} catch (GenericBusinessException e1) {
			GuiUtilities.showError(this,e1.getMessage());
		}
		if(!resultado.isEmpty()){
			if(resultado.size()==1){
				Cliente unCliente=(Cliente)resultado.get(0);
				txtOid.setText(Integer.toString(unCliente.getId()));
				txtNombre.setText(unCliente.getNombre());
				txtPrioridad.setText(Integer.toString(unCliente.getPrioridad()));
			}else{
				Vector<String> columns=new Vector<String>();
				String[] columnnames={"Id","Nombre","Prioridad"};
				for(int i=0;i<columnnames.length;i++)
					columns.addElement((String) columnnames[i]);
				tabModel.setRowCount(resultado.size());
				Vector lasRows=new Vector();
				for(int x=0;x<resultado.size();x++){
					Vector unaRow=new Vector();
					Cliente unCliente=(Cliente)resultado.get(x);
					unaRow.add(unCliente.getId());
					unaRow.add(unCliente.getNombre());
					unaRow.add(unCliente.getPrioridad());
					lasRows.add(unaRow);
				}
				tabModel.setDataVector(lasRows, columns);
			}
		}
	}

	/**
	 * This method initializes txtOid	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTxtOid() {
		if (txtOid == null) {
			txtOid = new JTextField();
			txtOid.setBounds(new Rectangle(100, 11, 133, 20));
			txtOid.setEditable(false);
		}
		return txtOid;
	}

	
	
	

}  //  @jve:decl-index=0:visual-constraint="10,10"
